//
//  MyMessageViewController.m
//  MIDI
//
//  Created by E.M.Game on 15/9/11.
//  Copyright (c) 2015年 QXSX. All rights reserved.
//

#import "MyMessageViewController.h"
#import "AppConfig.h"
#import "MyMessageTableCell.h"
#import "DelDataViewViewControl.h"
#import "QXNetWorkTool.h"
#import "APIAdress.h"
#import "MBProgressHUD+YC.h"
#import "UserDataSingleton.h"
#import "MyMessageModel.h"
#import "MJRefresh.h"
#import "CommFunc.h"
#import "MessageDetailViewController.h"

@interface MyMessageViewController ()<UITableViewDelegate , UITableViewDataSource,
                                        DelDataViewDeletage, QXNetWorkToolDelegate>

@property (weak, nonatomic) IBOutlet UITableView *tableView;

@property (strong, nonatomic) NSMutableArray *data;

@property (strong, nonatomic) MyMessageTableCell *cell;

@property (assign,nonatomic) int pageNum;

@property (assign,nonatomic) NSInteger delRow;

@end

@implementation MyMessageViewController

@synthesize data;

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.tableView.dataSource = self;
    
    self.tableView.delegate = self;
    
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    self.tableView.header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
    
    self.tableView.footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];

    self.data = [[NSMutableArray alloc] init];
    
    self.pageNum = 1;
    
    [self getData];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.data count];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.cell)
    {
        return [self.cell getHeight];
    }
    return 84;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    self.cell = [MyMessageTableCell cellWithTableView:tableView];
    
    if ([self.data count] > 0)
    {
        MyMessageModel *model = (MyMessageModel*)[self.data objectAtIndex:indexPath.row];
        if (model)
        {
            self.cell.titleLabel.text = model.title;
            self.cell.messageLabel.text = [self getMessage:model.message_cotent];
            
            self.cell.dateLabel.text = model.message_time;
        }
    }
    
    return self.cell;
}

- (NSString *)getMessage:(NSString *)str
{
    NSString *message = str;
    
    NSRange range;
    
    range = [message rangeOfString:@"音乐基础"];
    if (range.location != NSNotFound)
    {
        NSRange rangeLeftRaw = [message rangeOfString:@"<"];
        NSRange rangeRightRaw = [message rangeOfString:@">"];
        
        if (rangeLeftRaw.location != NSNotFound &&
            rangeRightRaw.location != NSNotFound)
        {
            NSRange locRange;
            locRange.length = rangeRightRaw.location - rangeLeftRaw.location - 1;
            locRange.location = rangeLeftRaw.location + 1;
            
            NSString *replaeceMessage = @"音乐理论 ";
            NSRange levelRange;
            levelRange = [message rangeOfString:@"等级1"];
            if (levelRange.location != NSNotFound)
            {
                replaeceMessage = [replaeceMessage stringByAppendingString:@"初级"];
                
                message = [message stringByReplacingCharactersInRange:locRange withString:replaeceMessage];
                
                return message;
            }
            
            levelRange = [message rangeOfString:@"等级2"];
            if (levelRange.location != NSNotFound)
            {
                replaeceMessage = [replaeceMessage stringByAppendingString:@"中级"];
                
                message = [message stringByReplacingCharactersInRange:locRange withString:replaeceMessage];
                
                return message;
            }
            
            levelRange = [message rangeOfString:@"等级3"];
            if (levelRange.location != NSNotFound)
            {
                replaeceMessage = [replaeceMessage stringByAppendingString:@"高级"];
                
                message = [message stringByReplacingCharactersInRange:locRange withString:replaeceMessage];
                
                return message;
            }
        }
    }
    return message;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSInteger idx = indexPath.row;
    MyMessageModel *message = [self.data objectAtIndex:idx];

    MessageDetailViewController *obj = [MessageDetailViewController create];
    obj.messageId = message.id;
    obj.messageTitle = message.title;
    
    [self.navigationController pushViewController:obj animated:YES];
}

-(UITableViewCellEditingStyle)tableView:(UITableView*)tableView  editingStyleForRowAtIndexPath:(NSIndexPath*)indexPath
{
    return UITableViewCellEditingStyleDelete;
}

-(void)tableView:(UITableView*)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath*)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete)
    {   
        self.delRow = [indexPath row];
        MyMessageModel *model = (MyMessageModel*)[self.data objectAtIndex:self.delRow];
        if (model)
        {
            [self delMessage:model.id];
        }
    }
}

-(NSString*)tableView:(UITableView*)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath*)indexpath
{
    return @"删除\n消息";
}


-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self configNavigationItem];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}

-(void) configNavigationItem
{
    [self.tabBarController configNavigationBarTintColor:UIColorRGBA(0, 0, 0, 1)];
    [self.navigationController.navigationBar setBarTintColor:MIDIColorOfNavigationBar];
    self.navigationController.navigationBar.barStyle = UIBarStyleBlack;
    self.navigationItem.title = @"我的消息";
    [self.navigationController.navigationBar setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIColor whiteColor],UITextAttributeTextColor, [UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:1.0],NSForegroundColorAttributeName,[UIFont fontWithName:@"Hiragino Sans GB" size:18.0],NSForegroundColorAttributeName,nil]];
    

    [self configNavigationBackAction:^{
        [self.navigationController popViewControllerAnimated:YES];
    }];
    
    [self configNavigationRightString:@"清空" textFont:[UIFont fontWithName:@"Hiragino Sans GB" size:13] textColor:UIColorRGBA(216, 216, 216, 1) andAction:^
         {
             if ([self.data count])
             {
                 [self pressRight];
             }
         }
    ];
    
}

-(void)pressRight
{
    DelDataViewViewControl *obj = [DelDataViewViewControl create];
    obj.view.backgroundColor = [UIColor clearColor];
    obj.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
    obj.modalPresentationStyle = UIModalPresentationOverCurrentContext;
    obj.definesPresentationContext = YES;
    obj.delDataDeletage = self;
    
    [self presentViewController:obj animated:YES completion:nil];
}

-(void)delData
{
    [self clear];
}

-(void)getData
{
    UserDataSingleton *userData = [UserDataSingleton shareInstance];
    if(![userData isLogin])
    {
        [userData pleaseLogin:self];
        return;
    }
    
    [MBProgressHUD showMessage:@"正在加载" toView:self.view];
    
    QXNetWorkTool *tool = [[QXNetWorkTool alloc]init];
    
    tool.QXNetWorkDelegate = self;
    
    NSString *pagenum = [NSString stringWithFormat:@"%d",self.pageNum];
    
    [tool GetDataFromServerWithPostMethodandInterfaceName:MyInfoInterface andParameter:
     @[@{
           @"user_id":userData.user_id,
           @"nowpage":pagenum,
           @"pagesize":@"10"}] tag:1];
}

-(void)delMessage:(NSString*)messageId
{
    [MBProgressHUD showMessage:@"正在加载" toView:self.view];
    
    QXNetWorkTool *tool = [[QXNetWorkTool alloc]init];
    
    tool.QXNetWorkDelegate = self;
    
    [tool GetDataFromServerWithPostMethodandInterfaceName:DelInfoInterface andParameter:
                    @[@{@"messge_id":messageId}] tag:2];
}

-(void)clear
{
    UserDataSingleton *userData = [UserDataSingleton shareInstance];
    if(![userData isLogin])
    {
        [userData pleaseLogin:self];
        return;
    }
    
    [MBProgressHUD showMessage:@"正在加载" toView:self.view];
    
    QXNetWorkTool *tool = [[QXNetWorkTool alloc]init];
    
    tool.QXNetWorkDelegate = self;
    
    [tool GetDataFromServerWithPostMethodandInterfaceName:ClearAllInfoInterface andParameter:
     @[@{@"user_id":userData.user_id}] tag:3];
}

#pragma mark 设置上下拉刷新

- (void)loadNewData
{
    [self.data removeAllObjects];
    self.pageNum = 1;
    
    [self getData];
    [self.tableView.header endRefreshing];
}

- (void)loadMoreData
{
    ++self.pageNum;
    
    [self getData];
    [self.tableView.footer endRefreshing];
}

- (void)GetFailResponse:(id)Response andTag:(int)tag
{
    [MBProgressHUD hideHUDForView:self.view];
    
    if (Response == nil)
        return;
    
    NSString *message = Response;
    
    [MBProgressHUD showError:message toView:self.view];
    
}

- (void)GetSuccessMessage:(id)message andTag:(int)tag
{
    NSString *mes = message;
    
    [MBProgressHUD showSuccess:mes toView:self.view];
}

-(void)GetSuccessResponse:(id)Response andTag:(int)tag
{
    [MBProgressHUD hideHUDForView:self.view];
    if (Response == nil)
    {
        return;
    }
    
    switch (tag)
    {
        case 1:
        {
            for (NSDictionary *dic in Response)
            {
                MyMessageModel *model = [MyMessageModel MyMessageModelWithDict:dic];
                [self.data addObject:model];
                
                [self.tableView reloadData];
            }
            break;
        }
        case 2:
        {
            [self.data removeObjectAtIndex:self.delRow];
            
            NSIndexPath *indexPath = [NSIndexPath indexPathForRow:self.delRow inSection:0];
            [self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
            
            break;
        }
        case 3:
        {
            [self.data removeAllObjects];
            [self.tableView reloadData];
            break;
        }
    }
}

	

@end



















